<template>
    <a-collapse-panel :key='row[valueFieldName]'>
        <template #header>{{row[labelFieldName]}}</template>
        <div :class='$style.rowContainer'>
            <template v-for='(item, i) in options'>
                <a-button type='dashed' @click='select(item)'>{{item[labelFieldName]}}</a-button>
            </template>
        </div>
        <template v-if='children.length > 0'>
            <XOptionCollapse :rows='children' :selectedApi='selectedApi' :valueFieldName='valueFieldName' :labelFieldName='labelFieldName' :childrenFieldName='childrenFieldName' />
        </template>
    </a-collapse-panel>
</template>

<script lang='ts' setup>
    import { reactive, ref } from "@vue/reactivity"

    const { selectedApi, row, labelFieldName, childrenFieldName } = withDefaults(defineProps<{
        row : any,
        valueFieldName : string,
        labelFieldName : string,
        childrenFieldName : string,
        selectedApi : (data : any) => void
    }>(), {
        row : () => ({}),
        valueFieldName : 'id',
        labelFieldName : 'label',
        childrenFieldName : 'children'
    })

    function select(item) {
        selectedApi(item)
    }

    const children = reactive<any[]>([])
    const options = reactive<any[]>([])

    function build(rows) {
        rows.forEach((row) =>{
            if(row[childrenFieldName] && row[childrenFieldName].length > 0) {
                children.push(row)
            }else {
                options.push(row)
            }
        })
    }

    if(row[childrenFieldName] && row[childrenFieldName].length > 0) {
        build(row[childrenFieldName])
    }

    
</script>

<style scoped module>
    .rowContainer{
        display: flex;
        gap: 10px;
        flex-wrap: wrap;
    }
</style>